<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Profile;
use App\Models\User;
use Illuminate\Support\Facades\Request;
use Maatwebsite\Excel\Facades\Excel;

class UserController extends Controller {

	public function __construct() {
		$this->middleware('role:system');
	}

	/**
	 * 进入用户管理页面
	 */
	public function getIndex() {
		$listUrl = url('admin/user');
		session(['listUrl' => $listUrl]);
		return view('admin/user_list');
	}

	/**
	 * 获取用户列表
	 */
	public function getPageList() {
		$limit = to_limit_lng(Request::input('limit'), 1);
		$users = User::orderBy('id', 'ASC')->paginate($limit);
		foreach ($users as $user) {
			$user->avatar = get_avatar($user->id);
			$user->profile;
		}
		return $this->response($users);
	}

	/**
	 * 获取用户信息
	 */
	public function getInfo() {
		$id = intval(Request::input('id'));
		$user = User::find($id);
		$user->profile;
		return $this->response($user);
	}

	/**
	 * 进入增加用户页面
	 */
	public function getAdd() {
		return view('admin/user_add');
	}

	/**
	 * 增加用户
	 */
	public function postInsert() {
		$username = safe(Request::input('username'), 50);
		$password = strval(Request::input('password'));
		$email = safe(Request::input('email'));
		$mobile = safe(Request::input('mobile'), 30);
		$status = Request::has('status') ? 0 : 1;

		$realname = safe(Request::input('realname'), 50);
		$cardid = safe(Request::input('cardid'), 30);
		$sex = safe(Request::input('sex'), 10);

		$n = User::where('username', $username)->count();
		if ($n > 0) {
			return $this->error('帐户已经存在');
		}
		if (!empty($email)) {
			if (User::where('email', $email)->count()) {
				return $this->error('邮箱已经存在');
			}
		}
		if (!empty($mobile)) {
			if (User::where('mobile', $mobile)->count()) {
				return $this->error('手机号已经被使用');
			}
		}

		$user = new User;
		$user->username = $username;
		$user->password = bcrypt($password);
		$user->email = $email;
		$user->mobile = $mobile;
		$user->realname = $realname;
		$user->sex = $sex;
		$user->status = $status;
		$user->save();

		$profile = new Profile;
		$profile->user_id = $user->id;
		$profile->cardid = $cardid;
		$profile->save();
		return $this->response('ok');
	}

	/**
	 * 编辑用户
	 */
	public function postUpdate() {
		$id = intval(Request::input('id'));
		$user = User::find($id);
		if (empty($user)) {
			return $this->error('无效的用户');
		}

		if (Request::exists('password')) {
			$password = strval(Request::input('password'));
			if (!empty($password)) {
				$user->password = bcrypt($password);
			}
		}

		if (Request::exists('email')) {
			$email = strval(Request::input('email'));
			if (empty($email) OR $user->email == $email) {
				$user->email = $email;
			} else {
				if (User::where('email', $email)->count()) {
					return $this->error('邮箱已经存在');
				}
				$user->email = $email;
			}
		}

		if (Request::exists('mobile')) {
			$mobile = strval(Request::input('mobile'));
			if (empty($mobile) OR $user->mobile == $mobile) {
				$user->mobile = $mobile;
			} else {
				if (User::where('mobile', $mobile)->count()) {
					return $this->error('手机号已经被使用');
				}
				$user->mobile = $mobile;
			}
		}

		if (Request::exists('realname')) {
			$realname = safe(Request::input('realname'), 50);
			$user->realname = $realname;
		}
		if (Request::exists('sex')) {
			$sex = safe(Request::input('sex'), 10);
			$user->sex = $sex;
		}
		if (Request::exists('cardid')) {
			$cardid = safe(Request::input('cardid'), 30);
			$user->profile->cardid = $cardid;
		}

		if (Request::exists('status')) {
			// 不能禁用管理员帐户
			$status = ($id == 1) ? 1 : to_limit_lng(Request::input('status'), 0, 1);
			$user->status = $status;
		}

		if ($user->save()) {
			$user->profile->save();
			return $this->response($user);
		}

		return $this->error('操作失败');
	}

	public function postUploadExcelFile() {
		$file = $_FILES['file1'];
		if (empty($file)) {
			return $this->error('无效的文件');
		}

		$title = $file['name'];
		$file_ext = strtolower(get_file_ext($file['name']));
		$tempFile = $file['tmp_name'];

		$allow_file_type = explode('|', 'xls|xlsx');
		if (!in_array($file_ext, $allow_file_type)) {
			return $this->error('无效的文件类型');
		}

		$target_path = '/upload/';
		$targetPath = public_path() . $target_path;
		if (!is_dir($targetPath)) {
			return $this->error('无效的上传目录');
		}

		$new_filename = uniqid() . '.' . $file_ext;
		$targetFile = $targetPath . $new_filename;
		if (!move_uploaded_file($tempFile, $targetFile)) {
			return $this->error('上传文件失败');
		}
		$users = $this->importUsers($targetFile);
		return $this->response($users);
	}

	private function importUsers($file) {
		$users = [];
		Excel::load($file, function ($reader) use (&$users) {
			$reader = $reader->getSheet(0);
			$results = $reader->toArray();
			array_shift($results);
			foreach ($results as $row) {
				$user = [
					'username' => $row[1],
					'password' => $row[2],
					'realname' => $row[3],
					'sex' => $row[4],
				];
				if ($this->createUser($user)) {
					array_push($users, $user);
				}
			}
		});
		unlink($file);
		return $users;
	}

	private function createUser($data) {
		extract($data);
		$n = User::where('username', $username)->count();
		if ($n > 0) {
			return false;
		}
		$user = new User;
		$user->username = safe($username, 50);
		$user->password = bcrypt($password);
		$user->realname = safe($realname, 50);
		$user->sex = safe($sex, 10);
		$user->email = '';
		$user->mobile = '';
		$user->status = 1;
		if ($user->save()) {
			$profile = new Profile;
			$profile->user_id = $user->id;
			$profile->cardid = '';
			$profile->save();
		}
		return true;
	}

	/**
	 * 删除用户
	 */
	public function postDelete() {
		$id = intval(Request::input('id'));
		if ($id == 1) {
			return $this->error('禁止删除系统管理员帐户');
		}
		$user = User::find($id);
		if (empty($user)) {
			return $this->error('无效的用户');
		}
		$user->delete();
		$user->roles()->sync([]);
		$user->profile->delete();
		$user->forceDelete();
		return $this->response('ok');
	}

}
